
package com.ai.networking.netty.service;

import com.ai.networking.netty.comm.CommonNetty;
import com.ai.entity.comm.SysNetty;
import com.ai.service.networking.ISysNettyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class ServerInit {

    @Resource
    ISysNettyService nettyService;

    @PostConstruct
    public void init() {
        log.info("================初始化数据========================");

        int[] ports = dataInit();
        serviceInit(ports);
    }

    /**
     * 数据初始化
     */
    public int[] dataInit() {
        List<SysNetty> nettyServerList = nettyService.getNativeStartServerList();
        int size = nettyServerList.size();
        int[] ports = new int[size];
        SysNetty nettyServer;
        for (int i = 0; i < size; i++) {
            nettyServer = nettyServerList.get(i);
            ports[i] = nettyServer.getPort();
            CommonNetty.NATIVE_SERVER_MAP.put(nettyServer.getCode(), nettyServer);
        }
        return ports;
    }

    /**
     * 服务初始化并启动
     */
    public void serviceInit(int... ports) {
        if (ports.length < 1) {
            return;
        }
        log.info("================1.启动时，开启监听========================");
        log.info("================2.启动时，NettyServer为null，启动Netty服务========================");

        Thread thread = new Thread(new NettyServer(ports));
        thread.start();
    }
}
